package main.demonutils.io;

import main.model.hexisland.HexIsland;

import javax.swing.*;


import java.io.*;
import java.util.ArrayList;

@Deprecated
public class AbstractIOController implements IOController {

    //private HexIslandCSVReader hexIslandCSVReader = new HexIslandCSVReader();
    //private HexIslandCSVWriter hexIslandCSVWriter = new HexIslandCSVWriter();

    private static final File DEFAULT_DIR = new File("data");
    //private final String DEFAULT_ISLAND = "default_terrain.isl";

    private File currentDir = DEFAULT_DIR;
    private JFileChooser fc;
    private final String[] LEGALEXTENSIONS = {"isl","cri","dem"};
    private ArrayList<String> selectedExtensions = new ArrayList<String>();
    
    private final int fileLength = 15; //The number of characters a file name can contain
    private final String legalName = "[a-zA-Z0-9_-]{1,"+fileLength+"}";
    //Lower, upper, num, u.score, dash.
    
    private File currentFile = null;
    //private boolean changed = false;
    
    public AbstractIOController(){
        fc = new JFileChooser(DEFAULT_DIR);
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        currentDir = DEFAULT_DIR;
    }


    public void saveIsland(HexIsland hexIsland){

    }

    public void loadIsland(HexIsland hexIsland){

    }


    
    public void addExtension(String extension){
    	if(extension == null 
    			|| selectedExtensions.contains(extension)) return;
    	for(String l : LEGALEXTENSIONS){
    		if(l.equalsIgnoreCase(extension)) selectedExtensions.add(extension);
    	}
    }
    
    public File getCurrentFile(){
    	return currentFile;
    }
    
    public void removeExtension(String extension){
    	if(extension == null) return;
    	selectedExtensions.remove(extension);
    }
    
    public File getCurrentDir(){
        if(currentDir.exists()) return currentDir;
        else return null;
    }
    
   public String getCurrentDirPathString(){
        if(currentDir.exists()) return currentDir.getAbsolutePath();
        else return "[unknown directory]";
   }

    public File[] getDirContent(){
        if(!currentDir.exists()) return null;

        ArrayList<String> legalExtensions = new ArrayList<String>();
        for(String extension : selectedExtensions){
            for(String legalExtension: LEGALEXTENSIONS){
                if(extension.equalsIgnoreCase(legalExtension)){
                    legalExtensions.add(extension);
                }
            }
        }
        final ArrayList<String> EXTENSIONS = legalExtensions;
        if(EXTENSIONS.size()<1) return null; //breakout early if there are no selected extentions (displays folders elsewise)

        FilenameFilter filter = new FilenameFilter(){
            public boolean accept(File dir, String name) {
                //Filter files beginning with '.' (hidden files)
                if(name.startsWith(".")) return false;
                String sname = name.substring(0, name.length() - 4);
                if(!sname.matches(legalName)) return false;
                for(String s : EXTENSIONS){
                    //Files with matching extensions
                    if(getExtension(name).equals(s)) return true;
                }
                return false; //if not a matching extension
            }
        };
        return currentDir.listFiles(filter);
    }


    private String getExtension(String n) {
        int i = n.lastIndexOf('.');
        if (i > 0 &&  i < n.length() - 1) {
            return n.substring(i+1).toLowerCase();
        } else {
            return null;
        }
    }

    /**
     * Uses the file chooser dialog to pick a directory.
     *
     * @return
     */
    public File chooseDirectory(){
        int returnVal = fc.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION){
            currentDir = fc.getSelectedFile();
            return currentDir;
        } else {
            return null;
        }
    }

    /**
     *
     * @param directory
     * @param type
     * @return
     */
    public File prepareNewFileLocation(File directory , String type){
        //Check that the target directory exists
        if(!directory.exists()){
            return null;
        }

        //Check that the extension is acceptable
        boolean acceptedType = false;
        for(String s : LEGALEXTENSIONS){
            if(s.equals(type)){
                acceptedType = true;
                break;
            }
        }
        if(!acceptedType) return null;

        //Loops round, asking for a name
        while (true){
            String s = (String)JOptionPane.showInputDialog(null,"File name:",
                    "Save As ...",JOptionPane.PLAIN_MESSAGE,null,null,null); //QUESTION_MESSAGE

            //Escape if cancelled
            if(s == null){return null;}
            if(s.length()>0){
                //Trim off user added extension
                if(getExtension(s).equals(type)){
                    s = s.subSequence(0, s.length()-4).toString();
                }
                //Check file length and legal characters
                if(s.length()>fileLength ||
                        !s.matches(legalName)){
                    JOptionPane.showMessageDialog(null,
                            "The file name contains ilegal characters or is too long."
                                    +"\nOnly letters, numbers, underscore or hyphens are accepted."
                                    +"\nNames should not exceed"+fileLength+" characters.");
                }

                //create the location, if it exists, check if it should be overwritten
                File f = new File(directory.getName()+File.separator+s+"."+type);
                if(f.exists()){
                    int n = JOptionPane.showConfirmDialog(
                            null,
                            "This following file already exists:\n"
                                    +f.getName()
                                    +"\nWould you like to overwrite it?",
                            "File Exists",JOptionPane.YES_NO_OPTION);
                    switch(n){
                        case 0: return f;
                        case 1: break;
                        default: return null;
                    }
                } else {
                    return f;
                }
            }
        }
    }
    

    
    /**
     * Deletes the file after consulting the user.
     * Returns true if the file is deleted or never existed to begin with.
     */
    public boolean deleteFile(File f){
        if(f.exists()){
            int n = JOptionPane.showConfirmDialog(null,
            "Are you sure you want to delete this file?",
            "Deleting File",JOptionPane.YES_NO_OPTION);
            if(n==0){
                try {
                    if(f.delete()){
                        System.out.print("\nDeleted : "+f.getName());
                        return true;
                    }
                }catch (SecurityException e){
                    return false;
                }
            }
        }
        return true;
    }

    private boolean edited = false;
	@Override
	public void setEdited(boolean edited) {this.edited = edited;}

	@Override
	public boolean getEdited() {return edited;}
}